import requests
import certifi
from django.conf import settings
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

# 持久会话 + 重试，缓解瞬时网络/服务端错误与读超时
_session = requests.Session()
_retry = Retry(
    total=3,
    connect=3,
    read=3,
    backoff_factor=0.7,
    status_forcelist=[429, 500, 502, 503, 504],
    allowed_methods=frozenset(["POST"])
)
_adapter = HTTPAdapter(max_retries=_retry, pool_connections=10, pool_maxsize=20)
_session.mount("https://", _adapter)
_session.mount("http://", _adapter)


def _call_deepseek(prompt, api_key, *, model="deepseek-chat", temperature=0.6, max_tokens=300, connect_timeout=5, read_timeout=120):
    url = getattr(settings, "DEEPSEEK_URL", "https://api.deepseek.com/v1/chat/completions")
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
    }
    payload = {
        "model": model,
        "messages": [
            {"role": "system", "content": "你是专业的分析助手，基于用户提供的出生日期、时间和性别，给出客观合理的分析。"},
            {"role": "user", "content": prompt},
        ],
        "temperature": float(temperature),
        "max_tokens": int(max_tokens),
        "stream": False,
    }
    timeout = (connect_timeout, read_timeout)

    resp = _session.post(url, json=payload, headers=headers, timeout=timeout, verify=certifi.where())
    resp.raise_for_status()
    data = resp.json()

    # 防御性提取
    choices = data.get("choices")
    if isinstance(choices, list) and choices:
        message = choices[0].get("message") if isinstance(choices[0], dict) else None
        if isinstance(message, dict):
            content = message.get("content")
            if content:
                return content
    raise ValueError("调用成功但响应格式异常，未找到内容字段。")